<template>
  <div class="menu-manage-page">

    <div class="flex-box-start">
        <el-input class="full-input" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
        <el-button type="primary" @click="addClass('')" icon="el-icon-plus" class="normal-btn square-btn add-menu-box">添加菜单</el-button>
    </div>

    <div class="custom-tree-container m-t-m">
      <div class="block left-box">
        <el-tree :data="data"
                 ref="tree"
                 node-key="primaryKey"
                 :props="defaultProps"
                 :default-expanded-keys="defaultKeys"
                 :filter-node-method="filterNode"
                 @node-expand="expandChange"
                 @node-collapse="collapseChange">

          <div class="custom-title" slot-scope="{ node, data }">
            <div class="title">{{ node.label }}</div>
            <div class="img">
              <el-image v-if="data.icon" :preview-src-list="[data.icon]" :src="data.icon" fit="contain"></el-image>
            </div>
            <div class="path"><span v-if="data.menuUrl">跳转地址：</span>{{data.menuUrl}}</div>
            <div class="btn">
              <el-button class="tree-btn" type="text" size="mini" @click.stop="addClass(data,'add')">添加子级</el-button>
              <el-button class="tree-btn" type="text" size="mini" @click.stop="addClass(data,'edit')">编辑</el-button>
              <el-button class="tree-btn danger" type="text" size="mini" @click.stop="removeData(node, data)">删除</el-button>
            </div>
          </div>
        </el-tree>
      </div>
    </div>
    <el-dialog class="menu-manage-dialog" :title="`${methodName}菜单`" :visible.sync="isClassShow" append-to-body
               :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="800px" >
      <el-form label-position="left" size="small" ref="baseInfo" :model="itemData" label-width="130px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="序号" prop="sortNo">
              <el-input-number class="full-width" v-model="itemData.sortNo" controls-position="right" :min="1" :max="10000"></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name" :rules="{required: true,message: '请输入菜单名称!',trigger: ['change']}">
              <el-input class="full-width" maxlength="15" placeholder="请输入菜单名称" v-model.trim="itemData.name"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单编码" prop="code" :rules="{required: true,message: '请输入菜单编码!',trigger: ['change']}">
              <el-input class="full-width" disabled maxlength="100" placeholder="请输入菜单编码" v-model.trim="itemData.code"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="权限编码">
              <el-input class="full-width" maxlength="100" placeholder="请输入菜单编码" v-model.trim="itemData.authCode"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12" style="height: 50px">
            <el-form-item label="是否配置" prop="showFlag">
              <el-switch v-model="itemData.showFlag" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单组值">
              <el-select v-model="itemData.groupNumber" class="full-width" placeholder="请选择菜单组值">
                <el-option v-for="(item) in menuGroupList" :key="item.key" :value="item.key" :label="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在位置" prop="locationList" :rules="{required: true,message: '请选择所在位置!',trigger: ['change']}">
              <el-select multiple v-model="itemData.locationList" class="full-width" placeholder="请选择所在位置">
                <el-option v-for="(item) in likeLocationList" :key="item.key" :value="item.key" :label="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type" :rules="{required: true,message: '请输入菜单类型!',trigger: ['change']}">
              <el-select v-model="itemData.type" class="full-width" placeholder="请选择菜单类型">
                <el-option v-for="(item) in menuTypeList" :key="item.key" :value="item.key" :label="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="itemData.type === 'redirect'||itemData.type === 'normal'">
            <el-form-item label="菜单跳转地址" prop="menuUrl" :rules="{required: true,message: '请输入菜单跳转地址!',trigger: ['change']}">
              <el-input class="full-width" maxlength="200" placeholder="请输入菜单跳转地址" v-model.trim="itemData.menuUrl"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24"  v-if="itemData.type === 'redirect'">
            <el-form-item label="单点登录地址" prop="ssoUrl">
              <el-input class="full-width" maxlength="200" placeholder="请输入单点登录地址" v-model.trim="itemData.ssoUrl"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="菜单描述">
              <el-input class="full-width" maxlength="100" placeholder="请输入菜单描述" v-model.trim="itemData.description"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="菜单图标">
                <UploadAlbum :height="100" :width="100" v-bind:cover-url.sync="itemData.icon"></UploadAlbum>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearData" size="small" class="el-button-reset">取 消</el-button>
        <el-button type="primary" size="small" @click="saveClass">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import { apiDictionary,apiMenuInfoCreate, apiMenuInfoDelete, apiMenuInfoUpdate, apiMenuInfoTree } from "../../api";

  export default {
    data() {
      return {
        data: [],
        menuGroupList: [],
        menuTypeList: [],
        defaultKeys: [],
        likeLocationList: [{key:"assetManagement",value:"阳光数字资管"},{key:"operationManagement",value:"阳光数字商管"},{key:"businessBuildingOperate",value:"商写运营"}],
        filterText: '',
        parentId: "",
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        isClassShow: false,
        itemData: {
          sortNo: 99,
          type: "button",
          name: "",
          menuUrl: "",
          description: "",
          icon: "",
          parentId: "",
          showFlag: 0,
          groupNumber: '',
          locationList: [],
          authCode: ''
        },
        methodName: '新增',
        dictionary: {},
        classArr: ["m-l-s", "m-l-m"]
      }
    },

    methods: {
      randomString (num) {  
        num = num || 18;
        var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
        a = t.length,
        n = "";
        for (let i = 0; i < num; i++) {
          n += t.charAt(Math.floor(Math.random() * a));
        }
        return n
      },
      async getDictionary () {
        let res = await apiDictionary()
        this.menuGroupList = res.menuGroup || []
        this.menuTypeList = res.menuType || []
      },
      handleDragEnd(draggingNode, dropNode, dropType, ev) {
        console.log('tree drag end: ', draggingNode, dropNode, dropType, ev);
      },
      //添加分类
      addClass(data, type) {
        console.log(data)
        this.clearData()
        if (type === 'edit') {
          data.locationList = data.location ? data.location.split(",") : []
          this.itemData = Object.assign({}, data);
          this.itemData.groupNumber = this.itemData.groupNumber?this.itemData.groupNumber+'':''
          this.methodName = '编辑'
        } else {
          this.methodName = '新增'
          this.itemData.categoryId = 'rent_menu';
          this.itemData.code = this.randomString()
          this.itemData.parentId = data.primaryKey ? data.primaryKey : this.parentId;
          this.itemData.level = data ? Number(data.level) + 1 : 0;
          this.itemData.sortNo = 99;
          this.itemData.showFlag= 0;
          this.itemData.icon= ""
          this.itemData.type = "button"
        }
        this.isClassShow = true;
        setTimeout(() => {
          this.$refs.baseInfo.clearValidate();
        }, 500);
      },

      //还原数据
      clearData() {
        this.isClassShow = false;
        for (let i in this.itemData) {
          this.itemData[i] = ""
        }
      },

      //删除
      removeData(node, data) {
        this.$confirm('您确定要删除该级目录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await apiMenuInfoDelete(data.primaryKey);
          if (res.success) {
            this.$message.success('删除成功！');
            this.getInfo();
          } else {
            this.$message.error(res.message);
          }
        });
      },

      //保存分类
      saveClass() {
        this.$refs.baseInfo.validate((valid) => {
          if (valid) {
            // 防止频繁保存
            if (this.ISPOST) {
              this.$message({
                message: "操作太频繁！",
                type: "warning"
              });
              return;
            }
            this.ISPOST = true;
            setTimeout(() => {
              this.ISPOST = false;
            }, 2000);
            this.saveBaseFn()
          } else {
          this.$message.error("你有必填项未填");
          }
        });
      },

      //数据入库
      async saveBaseFn() {
        this.itemData.location = this.itemData.locationList.join(",")
        let param = Object.assign({}, this.itemData);
        const data = this.itemData.primaryKey ?  await apiMenuInfoUpdate(param) : await apiMenuInfoCreate(param);
        if (data.success) {
          this.$message.success(data.message);
          this.isClassShow = false;
          this.getInfo()
        } else {
          this.$message.error(data.message);
        }
      },

      //过滤树
      filterNode(value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },

      //分类列表
      async getInfo() {
        this.getDictionary()
        let res = await apiMenuInfoTree({
          categoryId: 'rent_menu'
        });
        if(res.rows.length>0){
          this.data = res.rows[0].children;
          this.parentId = res.rows[0].primaryKey;
        }
      },

      // 展开节点
      expandChange(data,node) {
        this.defaultKeys.push(data.primaryKey)
      },

      // 关闭节点
      collapseChange(data,node) {
        this.defaultKeys = this.defaultKeys.splice(1,0,data.primaryKey);
      }

    },
    mounted() {
      this.getInfo()
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    }
  }
</script>
<style lang="scss">

  .menu-manage-page {
    padding: 20px 50px;
    .full-input{
        width: 100%;
    }
    .tree-btn{
        span{
            font-size: 14px;
        }
    }
    .square-btn{
        border-radius: 3px;
        padding: 5px 10px;
    }

    .add-menu-box {
      margin-left: 10px;
    }

    .custom-title {
      width: 100%;
      display: flex;
      font-size: 14px;
      line-height: 28px;
      align-items: center;

      .title {
        color: #666666;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 16px;
      }

      .img {
        width: 28px;
        height: 28px;

        .el-image {
          width: 28px;
          height: 28px;
          background: #efefef;
        }
      }

      .path {
        width: 400px;
        padding-left: 50px;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .btn {
        padding-left: 50px;
        width: 200px;
        text-align: right;
      }
    }


    .nav-btn-group {
      display: flex;
    }

    .el-tree-node__content {
      height: 32px;
    }

    .custom-tree-node {
      font-size: 14px;
      width: 100%;
      line-height: 30px;
      a {
        color: #606264;
      }
    }

    .nav-btn-group .el-button--mini {
      margin-top: 0;
    }

    .url-box {
      width: 430px;
      overflow: hidden;
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
    }
    .danger{
	    color: #f56c6c;
    }
  }

</style>
